﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using volva.Services;
using volva.Models;

namespace volva.Controllers
{
    public class StationController : Controller
    {
        //
        // GET: /Station/


        public ActionResult Index()
        {

            return View();
        }

        //
        // GET: /Station/Details/5

        public ActionResult Details(int id)
        {
            Station station = StationService.GetStationByID(id);
            ViewData["MostPopVideosOnStation"] = StationService.FindMostPopularVideosOnStation(id);
            ViewData["SerieID"] = StationService.GetSerieIdByVideoID(StationService.GetIdOfCurrentShow(id));
            ViewData["SerieName"] = StationService.GetSerieNameByID(StationService.GetSerieIdByVideoID(StationService.GetIdOfCurrentShow(id)));
            ViewData["TodaysSchedule"] = ScheduleService.GetTodaysSchedule(id, DateTime.Today);

            Video currentShow = StationService.GetCurrentShow(id);
            ViewData["CurrentShow"] = currentShow;

            ViewData["user"] = AccountService.GetUserByID(AccountService.GetUserIDByName(User.Identity.Name));

            if (currentShow != null)
            {
                StationService.AddVideoView(currentShow.id);
                StationService.AddStationView(currentShow.Station_id);
            }

            return View(station);
        }

        //
        // GET: /Station/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Station/Create

        [HttpPost]
        public ActionResult Create(Station model)
        {
            if (ModelState.IsValid)
            {
                model.createdDate = DateTime.Now;
                StationService.AddStation(model);

                WebUserRole role = new WebUserRole
                {
                    Station_id = model.id,
                    WebUser_id = AccountService.GetUserIDByName(User.Identity.Name),
                    access = 2,
                    confirmed = true
                };

                AccountService.AddRole(role);
                DataService.ddc.SubmitChanges();
                return RedirectToAction("Details/" + model.id, "Station");
            }
            else
            {
                ModelState.AddModelError("", "Villa");
            }
            return View();
        }
        
        //
        // GET: /Station/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Station/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Station/Delete/5
 
        /*
        *  The following functions are added by the development team.
        *  The above functions were automaticlly genetrated.
        */

        /// <summary>
        /// The index page for a specific station
        /// </summary>
        /// <param name="stationID">The ID of the station that will be displayed</param>
        /// <returns>The index page</returns>
        [HttpPost]
        public ActionResult Index(int stationID)
        {
            Station station = StationService.GetStationByID(stationID);
            ViewData["station"] = station;

            return View();
        }

        /// <summary>
        ///  The input page for editing Schedule
        /// </summary>
        /// <returns>Returns the default view for the Edit Schedule page</returns>
        /*public ActionResult Schedule()
        {

            ScheduleService.GetSchedule(
            return View();
        }*/

        public ActionResult Schedule(int id)
        {
            /*List<ScheduleItem> freeSchedule = ScheduleService.GetAvalibleShowTimes(id, DateTime.Today);
            List<ScheduleItem> openSchedule = ScheduleService.GetTodaysSchedule(id, DateTime.Today);
            List<ScheduleItem> schedule = new List<ScheduleItem>();

            for (int i = 0; i < 95; i++)
            {
                ScheduleItem item = new ScheduleItem();
                if ((freeSchedule.Count -1 ) < i)
                {
                    Bschedule.Add(openSchedule[i]);
                }
                else if ((openSchedule.Count -1 ) < i)
                {
                    schedule.Add(freeSchedule[i]);
                }
                else
                {
 
                        //item = (freeSchedule[i].airDateTime < openSchedule[i].airDateTime ? freeSchedule[i] : openSchedule[i]);
                        if (freeSchedule[i].airDateTime < openSchedule[i].airDateTime)
                        {
                            schedule.Add(freeSchedule[i]);
                            schedule.Add(openSchedule[i]);
                        }
                        else
                        {
                            schedule.Add(openSchedule[i]);
                            schedule.Add(freeSchedule[i]);
                        }
                        i++;
                }
            }

            ViewData["schedule"] = schedule;
            //ViewData["schedule"] = ScheduleService.GetTodaysSchedule(id, DateTime.Today);
            ViewData["station"] = StationService.GetStationByID(id);
            ViewData["reccomendation"] = StationService.GetReccomentation(id);
            */

            //List<ScheduleItem> schedule = new List<ScheduleItem>();
            ViewData["schedule"] = ScheduleService.GetTodaysSchedule(id, DateTime.Today);
            ViewData["station"] = StationService.GetStationByID(id);
            ViewData["reccomendation"] = StationService.GetReccomentation(id);

            // FUCK YOU WHARE, AND FUCK YOU DOLPHRIN!!!

            return View();
        }

        /// <summary>
        /// The logic for editing the schedule
        /// </summary>
        /// <param name="model"> The info from ScheduleItemModel that will be edited </param>
        /// <param name="action">"Add" to add to schedule, "Delete" to delete from schedule and "Change" to change the schedule</param>
        /// <returns> a confirmation page that the edit </returns>
        [HttpPost]
        public ActionResult ChangeSchedule(int id)
        {
            bool delete = Convert.ToBoolean(Request.Form["deleteVideo"]);
            int videoId = Convert.ToInt32(Request.Form["videoId"]);
            ViewData["stationId"] = StationService.GetVideoByID(videoId).Station_id;

            if (delete == true)
            {
                StationService.DeleteVideo(videoId);
            }
            else
            {
                int hour = Convert.ToInt32(Request.Form["hour"]);
                int minute = Convert.ToInt32(Request.Form["minute"]);

                DateTime date = DateTime.Today;
                date = date.AddHours(hour);
                date = date.AddMinutes(minute);

                ScheduleService.Add(videoId, date);
            }

            return View();
        }

        /// <summary>
        /// The input page for changing the basic info about the station
        /// </summary>
        /// <returns>Returns the default view before changes</returns>
        public ActionResult Change()
        {
            return View();
        }

        /// <summary>
        /// the Change station logic
        /// </summary>
        /// <param name="model">The info from StationModel that will be changed</param>
        /// <returns>returns that the data has been changed</returns>
        public ActionResult Change(Station model)
        {
            StationService.ChangeInfo(model);

            return View();
        }

        /// <summary>
        /// Deletes a station
        /// </summary>
        /// <returns>return the confirmation page (asking if you rely whant to do it)</returns>
        public ActionResult Delete()
        {
            return View();
        }

        /// <summary>
        /// The delete a station logic 
        /// </summary>
        /// <param name="stationID">The ID of the station that is to be deleted</param>
        /// <returns>returns a page saying the station has been removed</returns>
        public ActionResult Delete(int stationID)
        {
            StationService.DeleteStation(stationID);
            return View();
        }

        /// <summary>
        /// When producer sends in a suggestion to the manager about a video
        /// </summary>
        /// <param name="model">the info from VideoModel vill be sent to the manager</param>
        /// <returns>returns a video recommendation to the manager </returns>
        public ActionResult Recommend(Video model)
        {
            Message message = new Message();

            // Missing: StationService.GetAdmins(int stationId);
            // List<int> admins = StationService.GetAdmins(int stationId);

            

            //MessageService.Send();
            return View();
        }

        /// <summary>
        /// The delete a video logic
        /// </summary>
        /// <param name="videoID">the ID of the video that is to be deleted</param>
        /// <returns>returns a page saying that the video has been removed</returns>
        public ActionResult DeleteVideo(int videoID)
        {
            StationService.DeleteVideo(videoID);

            return View();
        }
        public ActionResult GiveRating()
        {
            int videoId = Convert.ToInt32(Request.Params["videoId"]);
            int rating = Convert.ToInt32(Request.Params["rating"]);

            Video video = StationService.GetVideoByID(videoId);

            StationService.AddStationRating(video.Station_id, rating);
       
            return View();
        }
        public ActionResult GiveVideoRating()
        {
            int videoId = Convert.ToInt32(Request.Params["videoId"]);
            int rating = Convert.ToInt32(Request.Params["rating"]);

            Video video = StationService.GetVideoByID(videoId);

            StationService.AddVideoRating(videoId, rating);
            StationService.AddStationRating(video.Station_id, rating);
            return View();
        }
        public ActionResult MyStations(int id)
        {
            ViewData["stations"] = StationService.GetStationsWhereAdminIs(id);

            return View();
        }
        public ActionResult Comments(int videoId)
        {
            ViewData["comments"] = StationService.GetVideoComment(videoId);
            return View();
        }
        /// <summary>
        /// Shows a form where a user can add a video to the system
        /// </summary>
        /// <returns></returns>
        public ActionResult AddVideo(int id)
        {
            ViewData["stationId"] = id;
            return View();
        }
        /// <summary>
        /// Sends the message model to the database
        /// </summary>
        /// <param name="model">The model for the video</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddVideo(Video model)
        {
            int stationId = Convert.ToInt32(Request.Params["stationId"]);
            model.embeddCode = System.Text.RegularExpressions.Regex.Match(model.embeddCode, "^http://(?<domain>([^./]+\\.)*youtube\\.com)(/v/|/watch\\?v=)(?<videoId>[A-Za-z0-9_-]{11})").Groups[4].Value;

            if (model.thumbnail == null)
            {
                model.thumbnail = "";
            }
            StationService.AddVideo(model, stationId);

            List<WebUser> admins = StationService.GetAdmins(stationId);
            //StationService.Reccomend(model, stationId);

            WebUser userFrom = AccountService.GetUserByID(AccountService.GetUserIDByName(User.Identity.Name));

            foreach (WebUser user in admins)
            {
                Message message = new Message
                {
                    WebUserTo = user,
                    subject = userFrom.username + " vill benda þér á myndband.",
                    body =  "<a href='/Account/Profile/" + userFrom.id + "'>" + userFrom.username + "</a>" +
                            " vill benda þér að bæta myndbandinu: " + 
                            "<a href='/Home/Watch/" + model.id + "'>" + model.name + "</a> á sjónvarpstöðina: " +
                            "<a href='/Station/Details/" + stationId + "'>"  + StationService.GetStationByID(stationId).name + "</a>.",
                    isNew = true,
                    WebUserFrom = userFrom
                };
                MessageService.Send(message);
            }

            ViewData["Message"] = "Myndbandinu var bætt inn.";

            return Redirect("/Station/Details/" + stationId);
            return View();
        }
        /*public ActionResult Report(int id)
        {
            StationService.ReportVideo(id, "lol");
            return View();
        }*/
        public ActionResult ListStations(int id)
        {
            ViewData["stations"] = StationService.GetStationsFromTo(id * 10, id + 10);
            return View();
        }
    }
}
